import React from "react";
import menuRoute from "routes/menuRoute";
import config from "config";
import { connect } from "react-redux";
import constants from "share/constants";
import errorMessage from "share/errorMessage";
import CustomTable from "components/custom-table";
import { setApprove } from "actions/cache";
import { messages, deepFullCopy, dealCache, queryCurrencyPrecision } from "share/common";
import { Form, Tabs, Tag, Popover, Table, Affix, message, Input, Button, Icon, Checkbox, Modal, Row, Col } from "antd";
const TabPane = Tabs.TabPane;
const Search = Input.Search;
import moment from "moment";
import debounce from "lodash.debounce";
import SearchArea from "components/search-area";
import ApproveBar from "components/template/approve-bar";
import approveService from "containers/approve/approve.service";
import "styles/approve/request/request.scss";
import checkingImg from "images/checking.png";
import loadingImg from "images/loading.png";
import openSlideFrame from "share/openSlideFrame";
import SlideLoanDetail from "../loan-billing/slide/slide-loan-detail";

class ApproveRequest extends React.Component {
  constructor(props) {
    super(props);
    this.entityObj = {
      1001: "requestForms",
      1002: "expenseForms",
      3001: "loanBillForms",
      4001: "othersForms",
    };
    this.entityApprovedObj = {
      1001: "requestApprovedForms",
      1002: "expenseApprovedForms",
      3001: "loanBillApprovedForms",
      4001: "othersApprovedForms",
    };
    this.state = {
      loading: false,
      passLoading: false,
      rejectLoading: false,
      tab: "approving",
      checkboxLoading: false,
      approvePendingCheckboxList: [],
      entityType: Number(props.params.entityType) || 1111, //是否为仪表盘来的
      approvedCheckboxList: [],
      searchForm: [
        {
          type: "input",
          id: "businessCode",
          label: messages("common.document.code") /*单号*/,
        },
        {
          type: "list",
          id: "applicantOIDs",
          label: messages("common.applicant") /*申请人*/,
          listType: "user_condition",
          labelKey: "fullName",
          valueKey: "userOID",
          listExtraParams: { roleType: "TENANT" },
        },
        {
          type: "list",
          id: "departmentOIDs",
          label: messages("common.department") /*部门*/,
          listType: "department",
          labelKey: "name",
          valueKey: "departmentOid",
          single: true,
        },
        {
          type: "items",
          id: "priceRange",
          items: [
            {
              type: "input",
              id: "minAmount",
              label: messages("request-4.key29") /*金额从*/,
            },
            {
              type: "input",
              id: "maxAmount",
              label: messages("request-4.key30") /*金额至*/,
            },
          ],
        },
        {
          type: "items",
          id: "dateRange",
          items: [
            {
              type: "date",
              id: "beginDate",
              label: messages("request-4.key31") /*日期从*/,
            },
            {
              type: "date",
              id: "endDate",
              label: messages("request-4.key32") /*日期至*/,
            },
          ],
        },
        {
          type: "list",
          id: "companyOIDs",
          label: messages("request-4.key12") /*公司*/,
          labelKey: "name",
          valueKey: "companyOID",
          listType: "permission_company",
          listExtraParams: { enabled: true },
        },
        {
          type: "multiple",
          id: "nodeOIDs",
          label: messages("request-4.key17") /*节点*/,
          options: [],
          getUrl: `${config.baseUrl}/api/approvals/approval/nodes/name?finished=false`,
          labelKey: "name",
          valueKey: "key",
          method: "get",
          renderOption: (option) => `${option.name}`,
        },
      ],
      approvePendingNum: 0,
      approvePendingSearchParams: {},
      approvedSearchParams: {},

      status: [
        {
          label: messages("request-4.key33") /*编辑中*/,
          value: "10011000",
          state: "processing",
        },
        {
          label: messages("request-4.key34") /*已撤回*/,
          value: "10011001",
          state: "warning",
        },
        {
          label: messages("request-4.key35") /*已驳回*/,
          value: "10011002",
          state: "error",
        },
        {
          label: messages("request-4.key36") /*审核驳回*/,
          value: "10011003",
          state: "error",
        },
        {
          label: messages("request-4.key26") /*审批中*/,
          value: "10021000",
          state: "processing",
        },
        {
          label: messages("request-4.key37") /*已通过*/,
          value: "10031000",
          state: "success",
        },
        {
          label: messages("request-4.key38") /*审核通过*/,
          value: "1004",
          state: "success",
        },
        {
          label: messages("request-4.key39") /*已付款*/,
          value: "1005",
          state: "success",
        },
        {
          label: messages("request-4.key40") /*还款中*/,
          value: "1006",
          state: "processing",
        },
        {
          label: messages("request-4.key41") /*已还款*/,
          value: "1007",
          state: "success",
        },
        {
          label: messages("request-4.key42") /*付款中*/,
          value: "1008",
          state: "processing",
        },
        {
          label: messages("request-4.key43") /*已停用*/,
          value: "1009",
          state: "default",
        },
      ],

      columns: [
        {
          title: messages("common.sequence") /*序号*/,
          dataIndex: "index",
          width: 80,
          render: (value, record, index) =>
            index +
            1 +
            this.state.pageSize * this.state.page +
            (record.approverOID && record.currentUserOID && record.approverOID !== record.currentUserOID
              ? `(${messages("common.proxy") /*代理*/})`
              : ""),
        },
        {
          title: messages("common.user.id") /*工号*/,
          dataIndex: "employeeID",
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.applicant") /*申请人*/,
          dataIndex: "applicant",
          render: (value) =>
            value && value.fullName ? (
              <Popover placement="topLeft" content={value.fullName}>
                {value.fullName}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.submit.date") /*提交日期*/,
          dataIndex: "submittedDate",
          sorter: true,
          width: 120,
          render: (value, record) => {
            let result = value
              ? moment(value).format("YYYY-MM-DD")
              : moment(record.lastSubmittedDate).format("YYYY-MM-DD");
            return result;
          },
        },
        {
          title: messages("common.document.name") /*单据名称*/,
          dataIndex: "formName",
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("request-4.key18") /*节点名称*/,
          dataIndex: "nodeName",
          width: 120,
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.document.code") /*单号*/,
          dataIndex: "businessCode",
          sorter: true,
          width: 120,
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("request-4.key13") /*事由*/,
          width: 150,
          dataIndex: "title",
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.currency") /*币种*/,
          dataIndex: "currencyCode",
          width: 48,
        },
        {
          title: messages("common.amount") /*金额*/,
          dataIndex: "amount",
          sorter: true,
          width: "8%",
          align: "right",
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
        },
        {
          title: messages("request-4.key14") /*本币金额*/,
          dataIndex: "baseCurrencyAmount",
          width: "8%",
          align: "right",
          sorter: true,
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode)),
        },
      ],
      approvedColumns: [
        {
          title: messages("common.sequence") /*序号*/,
          dataIndex: "index",
          width: 80,
          render: (value, record, index) =>
            index +
            1 +
            this.state.pageSize * this.state.page +
            (record.approverOID && record.currentUserOID && record.approverOID !== record.currentUserOID
              ? `(${messages("common.proxy") /*代理*/})`
              : ""),
        },
        {
          title: messages("common.user.id") /*工号*/,
          dataIndex: "employeeID",
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.applicant") /*申请人*/,
          dataIndex: "applicant",
          render: (value) =>
            value && value.fullName ? (
              <Popover placement="topLeft" content={value.fullName}>
                {value.fullName}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.submit.date") /*提交日期*/,
          dataIndex: "submittedDate",
          sorter: true,
          width: 120,
          render: (value, record) => {
            let result = value
              ? moment(value).format("YYYY-MM-DD")
              : moment(record.lastSubmittedDate).format("YYYY-MM-DD");
            return result;
          },
        },
        {
          title: messages("common.document.name") /*单据名称*/,
          dataIndex: "formName",
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.document.code") /*单号*/,
          dataIndex: "businessCode",
          sorter: true,
          width: 120,
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("request-4.key13") /*事由*/,
          width: 150,
          dataIndex: "title",
          render: (value) =>
            value ? (
              <Popover placement="topLeft" content={value}>
                {value}
              </Popover>
            ) : (
              "-"
            ),
        },
        {
          title: messages("common.currency") /*币种*/,
          dataIndex: "currencyCode",
          width: 48,
        },
        {
          title: messages("common.amount") /*金额*/,
          dataIndex: "amount",
          sorter: true,
          width: "8%",
          align: "right",
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
        },
        {
          title: messages("request-4.key14") /*本币金额*/,
          dataIndex: "baseCurrencyAmount",
          width: "8%",
          align: "right",
          sorter: true,
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.baseCurrencyCode)),
        },
        {
          title: messages("common.column.status") /*状态*/,
          dataIndex: "status",
          width: props.language.code === "zh_cn" ? "8%" : "13%",
          render: (value, record) => {
            return value ? (
              <Tag
                color={
                  constants.getTextByValue(String(value + "" + record.applicationType), "documentStatus", "color") ||
                  constants.getTextByValue(String(value + "" + record.rejectType), "documentStatus", "color") ||
                  constants.getTextByValue(String(value), "documentStatus", "color")
                }
              >
                {constants.getTextByValue(String(value + "" + record.applicationType), "documentStatus") ||
                  constants.getTextByValue(String(value + "" + record.rejectType), "documentStatus") ||
                  constants.getTextByValue(String(value), "documentStatus")}
              </Tag>
            ) : (
              <span>--</span>
            );
          },
        },
      ],
      sort: "",
      data: [],
      expandList: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
      },
      batchEnabled: false, //是否有批量审批
      allEnabled: false, //是否有全量审批
      isAll: false, //是否勾选中全量审批
      visible: false, //全量审批的弹框
      selectedRowKeys: [],
      selectedRows: [], //选中的单据OID
      cacheSearchData: {}, //缓存筛选的数据
      loadingApprovingForms: false, //加载待审批页的表单，只加载第一次
      loanBillForms: [],
      expenseForms: [],
      requestForms: [],
      othersForms: [],
      loadingApprovedForms: false, //加载已审批页的表单，只加载第一次
      loanBillApprovedForms: [],
      expenseApprovedForms: [],
      requestApprovedForms: [],
      othersApprovedForms: [],
    };
    this.approveRequestQuickView = menuRoute.getRouteItem("approve-request-quick-view", "key"); //快速查看申请单页
    this.handleSearch = debounce(this.handleSearch, 500);
  }

  componentDidMount() {
    let { approvePendingSearchParams, approvedSearchParams, entityType } = this.state;
    approvePendingSearchParams.entityType = entityType;
    approvedSearchParams.entityType = entityType;
    const { profile } = this.props;
    this.setState(
      {
        tab: this.props.location.query.tab === "approved" ? "approved" : "approving",
        // entityType: Number(this.props.location.query.entityType) || 1111,
        batchEnabled: profile["all.Approval.batch.Enable"],
        allEnabled: profile["approve.checkall.enable"],
      },
      () => {
        let initList = [
          {
            id: "entityType",
            single: true,
            items: [
              {
                label: messages("request-4.key7") /*单据类型*/,
                key: "entityType",
                options: this.getCheckListOptions(),
                expand: false,
                checked: [this.state.entityType],
              },
            ],
          },
        ];
        this.setState({
          approvedSearchParams,
          approvePendingSearchParams,
          approvePendingCheckboxList: initList,
          approvedCheckboxList: initList,
        });
        this.getCache();
      }
    );
  }

  getEntityType = (entityType) => {
    const { profile } = this.props;
    let result = entityType === 1111 ? [] : [entityType];
    if (!result.length) {
      result = [3001, 4001];
      if (!profile["er.opt.approval.disabled"]) {
        result.push(1002);
      }
      if (!profile["ca.opt.approval.web.disabled"]) {
        result.push(1001);
      }
    }
    return result;
  };

  getCheckListOptions = () => {
    const { profile } = this.props;
    let options = [{ label: messages("common.all") /*全部*/, value: 1111 }];
    if (!profile["er.opt.approval.disabled"]) {
      options.push({
        label: messages("request-4.key2") /*报销单*/,
        value: 1002,
      });
    }
    if (!profile["ca.opt.approval.web.disabled"]) {
      options.push({
        label: messages("request-4.key1") /*申请单*/,
        value: 1001,
      });
    }
    options.push({ label: messages("request-4.key3") /*借款单*/, value: 3001 });
    options.push({ label: messages("request-4.key4") /*其他*/, value: 4001 });
    return options;
  };

  getForms = (nextTab) => {
    const { tab: currentTab, loadingApprovingForms, loadingApprovedForms } = this.state;
    let searchTab = nextTab ? nextTab : currentTab;
    let entityArr = [1001, 1002, 3001, 4001];
    searchTab === "approving" &&
      !loadingApprovingForms &&
      approveService.getDocumentTypev2({ finished: false }).then((res) => {
        entityArr.map((entityType) => {
          this.setState(
            {
              loadingApprovingForms: true,
              [this.entityObj[entityType]]: res.data[entityType],
            },
            () => {
              if (this.state.entityType !== 1111) {
                this.getFormsOID(this.state.entityType);
              }
            }
          );
        });
      });
    searchTab === "approved" &&
      !loadingApprovedForms &&
      approveService.getDocumentTypev2({ finished: true }).then((res) => {
        entityArr.map((entityType) => {
          this.setState(
            {
              loadingApprovedForms: true,
              [this.entityApprovedObj[entityType]]: res.data[entityType],
            },
            () => {
              if (this.state.entityType !== 1111) {
                this.getFormsOID(this.state.entityType);
              }
            }
          );
        });
      });
  };

  //处理筛选缓存数据
  dealCache = (result) => {
    const { searchForm } = this.state;
    let defaultSearchForm = deepFullCopy(this.state.searchForm);
    if (result) {
      dealCache(searchForm, result);
      this.setState(
        {
          tab: result.tab ? result.tab : "approving",
          page: result.page,
          defaultSearchForm,
        },
        () => {
          this.getForms();
          this.search(result);
          this.props.dispatch(setApprove(null));
        }
      );
    }
  };

  onTabChange = (tab) => {
    const { params } = this.props;
    let { approvePendingCheckboxList, approvedCheckboxList, entityType, searchForm } = this.state;
    this.setState(
      {
        tab,
        sort: "",
        approvePendingSearchParams: {},
        approvedSearchParams: {},
        page: 0,
        pagination: { total: 0 },
      },
      () => {
        let initList = [
          {
            id: "entityType",
            single: true,
            items: [
              {
                label: messages("request-4.key7") /*单据类型*/,
                key: "entityType",
                options: this.getCheckListOptions(),
                expand: false,
                checked: [1111],
              },
            ],
          },
        ];
        this.setState({
          approvePendingCheckboxList: initList,
          approvedCheckboxList: initList,
        });
        if (tab === "approved") {
          entityType = Number(params.entityType) || 1111;
          this.dealCache({
            tab,
            formOIDs: [],
            page: 0,
            beginDate: moment().subtract(3, "month"),
            endDate: moment(),
            entityType,
          });
        } else {
          entityType = Number(params.entityType) || 1111;
          searchForm.map((condition) => {
            if (condition.id === "dateRange") {
              condition.items = [
                {
                  type: "date",
                  id: "beginDate",
                  label: messages("request-4.key31") /*日期从*/,
                },
                {
                  type: "date",
                  id: "endDate",
                  label: messages("request-4.key32") /*日期至*/,
                },
              ];
            }
          });
          this.setState({ searchForm }, () => {
            this.dealCache({ tab, page: 0, entityType });
          });
        }
        this.setState(
          {
            entityType,
            approvedCheckboxList,
            approvePendingCheckboxList,
          },
          () => {
            this.checkboxChange({
              entityType: Number(params.entityType) || 1111,
            });
          }
        );
      }
    );
  };

  getFormsOID = (entityType) => {
    let { tab, approvePendingCheckboxList, approvedCheckboxList } = this.state;
    let formOIDs = this.state[tab === "approving" ? this.entityObj[entityType] : this.entityApprovedObj[entityType]];
    let options = [],
      newCheckboxList = [];
    let checkboxList = tab === "approving" ? approvePendingCheckboxList : approvedCheckboxList;
    formOIDs &&
      Object.keys(formOIDs).map((key) => {
        options.push({ label: key, value: formOIDs[key].join(",") });
      });
    newCheckboxList.push(checkboxList[0]);
    newCheckboxList.push({
      id: "formOIDs",
      items: [
        {
          label: messages("common.document.name") /*单据名称*/,
          key: "formOID",
          options: [],
          checkAllOption: true,
        },
      ],
    });
    newCheckboxList.map((form) => {
      if (form.id === "formOIDs") {
        form.items.map((item) => {
          item.key === "formOID" && (item.options = options);
        });
      }
    });
    this.setState(
      {
        [tab === "approving" ? "approvePendingCheckboxList" : "approvedCheckboxList"]: newCheckboxList,
      },
      () => {}
    );
  };

  checkboxChange = (res) => {
    let { tab, approvePendingCheckboxList, approvedCheckboxList } = this.state;
    if (typeof res == "object" && res) {
      this.setState(
        {
          entityType: res.entityType,
        },
        () => {
          if (res.entityType === 1111) {
            let checkboxList = tab === "approving" ? approvePendingCheckboxList : approvedCheckboxList,
              newCheckboxList = [];
            newCheckboxList.push(checkboxList[0]);
            this.setState({
              [tab === "approving" ? "approvePendingCheckboxList" : "approvedCheckboxList"]: newCheckboxList,
            });
          } else {
            this.getFormsOID(res.entityType);
          }
        }
      );
    }
  };

  getList = () => {
    const {
      tab,
      page,
      pageSize,
      entityType,
      approvePendingSearchParams,
      approvePendingCheckboxList,
      approvedCheckboxList,
      approvedSearchParams,
      sort,
      cacheSearchData,
      isAll,
    } = this.state;
    let resultEntityType = this.getEntityType(entityType);
    cacheSearchData.page = page;
    if (sort) {
      cacheSearchData.sort = sort;
    }
    if (sort && tab === "approved") {
      approvedSearchParams.sort = sort;
    }
    if (sort && tab !== "approved") {
      approvePendingSearchParams.sort = sort;
    }
    this.setState({ loading: true });
    approveService
      .getApproveList(
        tab === "approved",
        resultEntityType,
        page,
        pageSize,
        tab === "approved" ? approvedSearchParams : approvePendingSearchParams
      )
      .then((res) => {
        let data = [];
        let nodeOIDList = [];
        res.data.map((item) => {
          if (item.addSign) {
            item.nodeName = messages("request-4.key15") /*自选审批*/;
          }
          if (tab !== "approved" && item.nodeOID) {
            nodeOIDList.push(item.nodeOID);
          }
          data.push(item);
        });
        if (!(tab === "approved")) {
          this.setState({
            approvePendingNum: Number(res.headers["x-total-count"]) || 0,
          });
        }
        if (nodeOIDList.length) {
          approveService
            .getApproveNodeName(nodeOIDList)
            .then((resq) => {
              data.map((oneData) => {
                if (oneData.nodeOID) {
                  resq.data.map((node) => {
                    if (oneData.nodeOID === node.ruleApprovalNodeOID) {
                      if (oneData.nodeAddSign) {
                        oneData.nodeName = node.name + messages("request-4.key16") /*(加签)*/;
                      } else {
                        oneData.nodeName = node.name;
                      }
                    }
                  });
                }
              });
              this.setState(
                {
                  loading: false,
                  data,
                },
                () => {
                  this.processExpandList();
                  isAll && this.handleSelectIsAll();
                }
              );
            })
            .catch((err) => {
              this.setState(
                {
                  loading: false,
                  data,
                },
                () => {
                  this.processExpandList();
                  isAll && this.handleSelectIsAll();
                }
              );
            });
        } else {
          this.setState(
            {
              loading: false,
              data,
            },
            () => {
              this.processExpandList();
              isAll && this.handleSelectIsAll();
            }
          );
        }
        this.setState({
          pagination: {
            total: Number(res.headers["x-total-count"]) || 0,
            current: page + 1,
            onChange: this.onChangePaper,
          },
        });
      })
      .catch((err) => {
        errorMessage(err.response);
        this.setState({
          loading: false,
        });
      });
  };

  //处理列表页标签展示
  processExpandList = () => {
    let { data } = this.state;
    let expandList = [];
    data.map((item) => {
      let isExpand = false; //是否有标签
      if (item.pending) {
        //暂挂标签
        isExpand = true;
      }
      if (item.warningList && JSON.parse(item.warningList)) {
        let warningList = JSON.parse(item.warningList);
        warningList.map((warnItem) => {
          if (warnItem.showFlag === 1) {
            isExpand = true;
          }
        });
      }
      if (isExpand) {
        item.isExpand = true;
        expandList.push(item.entityOID + item.approverOID);
      }
    });
    this.setState({ data, expandList });
  };

  expandedRowRender = (record) => {
    let expandedFlag = record.isExpand;
    let warningList = record.warningList ? JSON.parse(record.warningList) : [];
    return expandedFlag ? (
      <div>
        {record.pending && <div>{messages("request-4.key44") /*标签：暂挂*/}</div>}
        {warningList.map((warnItem) => {
          return warnItem.showFlag === 1 ? (
            <div>
              {" "}
              {messages("request-4.key45") /*标签：*/}
              {warnItem.title}
            </div>
          ) : null;
        })}
      </div>
    ) : null;
  };

  handleExpand = (isExpand, record) => {
    let { expandList } = this.state;
    let rowKey = record.entityOID + record.approverOID;
    isExpand ? expandList.addIfNotExist(rowKey) : expandList.delete(rowKey);
    this.setState({ expandList });
  };

  search = (values) => {
    if (Number(this.props.params.entityType) && !values.entityType) {
      values.entityType = Number(this.props.params.entityType);
    }
    this.setCache({ ...values });
    values.beginDate && (values.beginDate = moment(values.beginDate).format("YYYY-MM-DD"));
    values.endDate && (values.endDate = moment(values.endDate).format("YYYY-MM-DD"));
    this.setState(
      {
        entityType: values.entityType ? values.entityType : 1111,
        [this.state.tab === "approving" ? "approvePendingSearchParams" : "approvedSearchParams"]: values,
        page: values.page ? values.page : 0,
        pagination: { total: 0 },
      },
      () => {
        this.getList();
      }
    );
  };

  //存储筛选数据缓存
  setCache = (result) => {
    const { tab, page } = this.state;
    result.tab = tab;
    result.page = page;
    this.setState({ cacheSearchData: result });
  };

  //获取筛选数据缓存
  getCache = () => {
    let result = this.props.approve;
    let { tab, selectedRowKeys, selectedRows } = this.state;
    if (result && JSON.stringify(result) !== "{}") {
      let { approvePendingCheckboxList, approvedCheckboxList, isAll } = result;
      if (tab === "approving") {
        approvePendingCheckboxList.map((form, index) => {
          if (form.id === "formOIDs") {
            approvePendingCheckboxList[index].items[0].checked = result["formOIDsLable"] || [];
          }
        });
        selectedRowKeys = result["selectedRowKeys"] || [];
        selectedRows = result["selectedRows"] || [];
      } else {
        approvedCheckboxList.map((form, index) => {
          if (form.id === "formOIDs") {
            approvedCheckboxList[index].items[0].checked = result["formOIDsLable"] || [];
          }
        });
      }
      this.setState(
        {
          isAll,
          cacheSearchData: result,
          approvePendingCheckboxList,
          approvedCheckboxList,
          selectedRowKeys,
          entityType: result["entityType"],
          selectedRows,
        },
        () => {
          this.dealCache(result);
        }
      );
    } else {
      let defaultSearchForm = deepFullCopy(this.state.searchForm);
      this.getForms();
      this.getList();
      this.setState({ defaultSearchForm });
    }
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.setCache(this.state.cacheSearchData);
      });
    }
  };

  //详情跳转
  handleRowClick = (record) => {
    let {
      cacheSearchData,
      selectedRowKeys,
      selectedRows,
      approvedCheckboxList,
      approvePendingCheckboxList,
      entityType,
      isAll,
      tab,
    } = this.state;
    cacheSearchData.selectedRowKeys = selectedRowKeys;
    cacheSearchData.selectedRows = selectedRows;
    cacheSearchData.approvedCheckboxList = approvedCheckboxList;
    cacheSearchData.approvePendingCheckboxList = approvePendingCheckboxList;
    cacheSearchData.entityType = entityType;
    cacheSearchData.isAll = isAll;
    this.props.dispatch(setApprove(cacheSearchData));
    switch (record.entityType) {
      case 1001: //申请单
        openSlideFrame.openRequestReport(
          {
            formOID: record.formOID,
            applicationOID: record.entityOID,
            status: tab,
            approverOID: record.approverOID,
            entry: "approve",
          },
          {
            afterClose: (value) => {
              typeof value === "boolean" && value && this.getList();
            },
          },
          this
        );
        break;
      case 1002: //报销单
        openSlideFrame.openExpenseReport(
          {
            expenseReportOID: record.entityOID,
            approverOID: record.approverOID,
            status: tab,
            entry: "approve",
          },
          {
            afterClose: (value) => {
              typeof value === "boolean" && value && this.getList();
            },
          },
          this
        );
        break;
      case 3001: //借款单
        openSlideFrame.openLoanReport(
          {
            formOID: record.formOID,
            loanBillOID: record.entityOID,
            status: tab,
            approverOID: record.approverOID,
            pathname: this.props.location.pathname,
            entry: "approve",
          },
          {
            noPadding: true,
            content: SlideLoanDetail,
            afterClose: (value) => typeof value === "boolean" && value && this.getList(),
          },
          this
        );
        break;
      case 4001: //其他
        openSlideFrame.openOtherReport(
          {
            formOID: record.formOID,
            applicationOID: record.entityOID,
            backType: "history",
            status: tab,
            approverOID: record.approverOID,
            entry: "approve",
          },
          {
            afterClose: (value) => {
              typeof value === "boolean" && value && this.getList();
            },
          },
          this
        );
        break;
    }
  };

  handleTableChange = (pagination, filters, sorter) => {
    let page = pagination.current;
    let sort = "";
    if (sorter.order) {
      if (sorter.columnKey === "amount") {
        sort = `totalAmount,${sorter.order === "ascend" ? "ASC" : "DESC"}`;
      } else {
        sort = `${sorter.columnKey},${sorter.order === "ascend" ? "ASC" : "DESC"}`;
      }
    }
    this.setState(
      {
        page: page - 1,
        sort,
      },
      () => {
        this.getList();
      }
    );
  };

  handleQuickView = () => {
    let url = this.approveRequestQuickView.url;
    this.context.router.push(url);
  };

  //刷新selectedRowKeys
  refreshSelectedRowKeys = () => {
    const { selectedRows } = this.state;
    let selectedRowKeys = [];
    selectedRows.length &&
      selectedRows.map((row) => {
        let record = JSON.parse(row);
        selectedRowKeys.push(`${record.entityOID}${record.approverOID}`);
      });
    this.setState({ selectedRowKeys });
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    if (selectedRowKeys.length > 20) {
      message.warning(messages("request-4.key46") /*最多选择20条数据*/);
    } else {
      this.setState({ selectedRowKeys });
    }
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  onSelectRow = (record, selected) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    let item = JSON.stringify({
      approverOID: record.approverOID,
      entityOID: record.entityOID,
      entityType: record.entityType,
    });
    selected ? selectedRows.push(item) : selectedRows.delete(item);
    selectedRows.length <= 20 &&
      this.setState({ selectedRows }, () => {
        this.refreshSelectedRowKeys();
      });
  };

  //全选
  onSelectAllRow = (selected) => {
    let selectedRows = deepFullCopy(this.state.selectedRows);
    this.state.data.map((item) => {
      let row = JSON.stringify({
        approverOID: item.approverOID,
        entityOID: item.entityOID,
        entityType: item.entityType,
      });
      selected ? !item.pending && selectedRows.addIfNotExist(row) : selectedRows.delete(row);
    });
    selectedRows.length <= 20 &&
      this.setState({ selectedRows }, () => {
        this.refreshSelectedRowKeys();
      });
  };

  //审批操作
  handleApprove = (value, type) => {
    const { isAll } = this.state;
    let entities = [];
    this.state.selectedRows.map((item) => {
      entities.push(JSON.parse(item));
    });
    let params = {
      entities,
      approvalTxt: value,
    };

    if (isAll) {
      this.handleApproveAll(value, type);
      return;
    }
    this.setState({
      [type === "pass" ? "passLoading" : "rejectLoading"]: true,
    });
    approveService[type === "pass" ? "handleRequestApprovePass" : "handleRequestApproveReject"](params)
      .then((res) => {
        if (res.status === 200) {
          message.success(
            messages("request-4.key19", {
              arg1: res.data.successNum,
            }) /*成功处理 {arg1} 笔单据*/ +
              ", " +
              messages("request-4.key20", {
                arg1: res.data.failNum,
              }) /*失败 {arg1} 笔单据*/
          );
          this.setState({ passLoading: false, rejectLoading: false });
          this.setState(
            {
              tab: "approving",
              page: 0,
              pagination: { total: 0 },
              selectedRowKeys: [],
              selectedRows: [],
            },
            () => {
              this.getList();
            }
          );
        }
      })
      .catch((e) => {
        this.setState({ passLoading: false, rejectLoading: false });
        message.error(`${messages("common.operate.filed") /*操作失败*/}，${e.response.data.message}`);
      });
  };

  //关闭全量审批的提示弹框
  handleClose = () => {
    this.setState({ visible: false });
  };

  //全量审批
  handleApproveAll = (value, type) => {
    const { approvePendingSearchParams, entityType } = this.state;
    let resultEntityType = this.getEntityType(entityType);
    let body = {
      approvalTxt: value,
      operationType: type === "pass" ? 1001 : 1002,
    };
    this.setState({
      [type === "pass" ? "passLoading" : "rejectLoading"]: true,
    });
    approveService
      .handleAllApprove(resultEntityType, approvePendingSearchParams, body)
      .then((res) => {
        this.setState({
          passLoading: false,
          rejectLoading: false,
          visible: true,
        });
        this.getList();
      })
      .catch((e) => {
        this.setState({ passLoading: false, rejectLoading: false });
        message.error(`${messages("common.operate.filed") /*操作失败*/}，${e.response.data.message}`);
      });
  };

  searchClear = () => {
    this.setState({ cacheSearchData: {} });
    this.setCache({});
    let { defaultSearchForm } = this.state;
    this.checkboxChange({ entityType: 1111 });
    this.setState(
      {
        [this.state.tab === "approving" ? "approvePendingSearchParams" : "approvedSearchParams"]: {},
        page: 0,
        searchForm: deepFullCopy(defaultSearchForm),
        pagination: { total: 0 },
      },
      () => {
        this.getList();
      }
    );
  };

  handleSearch = (value) => {
    this.setCache({ ...value });
    let { tab, approvePendingSearchParams, approvedSearchParams } = this.state;
    if (tab === "approved") {
      approvedSearchParams.businessCode = value;
    }
    if (tab !== "approved") {
      approvePendingSearchParams.businessCode = value;
    }

    this.setState(
      {
        page: 0,
        pagination: {
          total: 0,
          current: 1,
        },
        approvedSearchParams,
        approvePendingSearchParams,
      },
      () => {
        this.getList();
      }
    );
  };

  //已审批页面 搜索条件中要去除节点, 待审批页面，搜索条件增加节点搜索
  processSearchForm = (searchForm) => {
    const { tab } = this.state;
    let nodeIndex = -1;
    searchForm.map((condition, index) => {
      if (condition.id === "nodeOIDs") {
        nodeIndex = index;
      }
    });
    if (tab === "approving" && nodeIndex === -1) {
      searchForm.push({
        type: "multiple",
        id: "nodeOIDs",
        label: messages("request-4.key17") /*节点*/,
        options: [],
        getUrl: `${config.baseUrl}/api/approvals/approval/nodes/name?finished=false`,
        labelKey: "name",
        valueKey: "key",
        method: "get",
        renderOption: (option) => `${option.name}`,
      });
    }
    if (tab === "approved" && nodeIndex > -1) {
      searchForm.splice(nodeIndex, 1);
    }
    return searchForm;
  };

  handleChangeIsAll = (value) => {
    this.setState({ isAll: value });
    if (value) {
      this.handleSelectIsAll();
    } else {
      this.setState({ selectedRows: [] }, () => {
        this.refreshSelectedRowKeys();
      });
    }
  };

  //勾选了全部审批，当前页的单据都要勾选上
  handleSelectIsAll = () => {
    const { data } = this.state;
    let selectedRows = [];
    data.map((item) => {
      let row = JSON.stringify({
        approverOID: item.approverOID,
        entityOID: item.entityOID,
        entityType: item.entityType,
      });
      selectedRows.push(row);
    });
    this.setState({ selectedRows }, () => {
      this.refreshSelectedRowKeys();
    });
  };

  render() {
    const {
      loading,
      tab,
      entityType,
      searchForm,
      approvePendingCheckboxList,
      approvedCheckboxList,
      columns,
      approvedColumns,
      data,
      pagination,
      batchEnabled,
      selectedRowKeys,
      selectedRows,
      passLoading,
      rejectLoading,
      expandList,
      allEnabled,
      isAll,
      visible,
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow,
      onSelectAll: this.onSelectAllRow,
      getCheckboxProps: () => ({ disabled: isAll }),
    };
    if (tab === "approving") {
      approvePendingCheckboxList.map((form, index) => {
        if (form.id === "entityType") {
          approvePendingCheckboxList[index].items[0].checked[0] = entityType || 1111;
        }
      });
    } else {
      approvedCheckboxList.map((form, index) => {
        if (form.id === "entityType") {
          approvedCheckboxList[index].items[0].checked[0] = entityType || 1111;
        }
      });
    }
    return (
      <div className={`approve-request ${selectedRows.length && tab === "approving" ? "bottom-100" : ""}`}>
        <Tabs activeKey={tab} onChange={this.onTabChange}>
          <TabPane tab={`${messages("request-4.key21") /*待审批*/}`} key="approving" disabled={loading} />
          <TabPane tab={messages("request-4.key22") /*已审批*/} key="approved" disabled={loading} />
        </Tabs>
        {tab === "approving" && (
          <SearchArea
            searchForm={this.processSearchForm(searchForm)}
            checkboxListForm={approvePendingCheckboxList}
            isReturnLabel
            checkboxChange={this.checkboxChange}
            submitHandle={this.search}
            clearHandle={this.searchClear}
          />
        )}
        {tab === "approved" && (
          <SearchArea
            searchForm={this.processSearchForm(searchForm)}
            checkboxListForm={approvedCheckboxList}
            isReturnLabel
            checkboxChange={this.checkboxChange}
            submitHandle={this.search}
            clearHandle={this.searchClear}
          />
        )}
        <div className="table-header" style={{ marginBottom: 22 }}>
          <div className="table-header-title">
            {
              messages("common.total", {
                arg1: pagination.total,
              }) /*共搜索到 {arg1} 条数据*/
            }
            {tab === "approving" &&
              batchEnabled &&
              ` / ${
                messages("common.total.selected", {
                  arg1: isAll ? pagination.total : selectedRows.length,
                }) /*已选 {arg1} 条*/
              }`}
          </div>
          <div className="table-header-buttons">
            {tab === "approving" && !window.ISIE9 && (
              <Button type="primary" onClick={this.handleQuickView} ref="approveQuickView">
                {messages("request-4.key23") /*快速查看*/}
              </Button>
            )}
            {tab === "approving" && batchEnabled && allEnabled && (
              <Checkbox
                style={{ marginLeft: "20px" }}
                checked={isAll}
                onChange={(e) => this.handleChangeIsAll(e.target.checked)}
              >
                {messages("request-4.key24") /*全选全部单据*/}
              </Checkbox>
            )}
            <Search
              className="input-search"
              style={{ paddingRight: 0 }}
              maxLength={100}
              placeholder={messages("request-4.key25") /*请输入单号*/}
              onChange={(e) => this.handleSearch(e.target.value)}
            />
          </div>
        </div>
        {tab === "approving" && (
          <CustomTable
            allColumns={columns}
            localKey="request-approving-list-v2"
            tableOption={{
              rowKey: (record) => record.entityOID + record.approverOID,
              size: "middle",
              loading,
              rowSelection: tab === "approving" && batchEnabled ? rowSelection : null,
              pagination,
              columns,
              rowClassName: (record) => (record.isExpand ? "" : "row-expand-display-none"),
              expandedRowRender: (record) => this.expandedRowRender(record),
              expandedRowKeys: expandList,
              onExpand: this.handleExpand,
              onChange: this.handleTableChange,
              onRow: (record) => ({
                onClick: () => this.handleRowClick(record),
              }),
              bordered: true,
              dataSource: data,
            }}
          />
        )}
        {tab === "approved" && (
          <CustomTable
            allColumns={approvedColumns}
            localKey="request-approved-list-v2"
            tableOption={{
              rowKey: (record) => record.entityOID + record.approverOID,
              size: "middle",
              loading,
              rowSelection: null,
              pagination,
              columns: approvedColumns,
              rowClassName: (record) => (record.isExpand ? "" : "row-expand-display-none"),
              expandedRowRender: (record) => this.expandedRowRender(record),
              expandedRowKeys: expandList,
              onExpand: this.handleExpand,
              onChange: this.handleTableChange,
              onRow: (record) => ({
                onClick: () => this.handleRowClick(record),
              }),
              bordered: true,
              dataSource: data,
            }}
          />
        )}
        <Affix
          offsetBottom={0}
          className={`bottom-bar-approve ${selectedRows.length && tab === "approving" ? "show" : "hide"}`}
        >
          <ApproveBar
            passLoading={passLoading}
            rejectLoading={rejectLoading}
            batchNumber={selectedRows.length}
            allLoading={passLoading || rejectLoading}
            handleApprovePass={(value) => this.handleApprove(value, "pass")}
            handleApproveReject={(value) => this.handleApprove(value, "reject")}
          />
        </Affix>
        <Modal
          title={messages("request-4.key26") /*审批中*/}
          visible={visible}
          onCancel={this.handleClose}
          maskClosable={false}
          footer={[
            <Button key="sure" type="primary" onClick={this.handleClose}>
              {messages("common.ok") /*确定*/}
            </Button>,
          ]}
        >
          <Row type="flex" gutter={16} align="middle" className="approve-all-modal">
            <Col span={8} style={{ textAlign: "right" }}>
              <img src={checkingImg} className="img-inner" />
              <img src={loadingImg} className="img-out rotation" />
            </Col>
            <Col span={16}>
              <div>{messages("request-4.key27") /*批量审批中......*/}</div>
              <div>
                {
                  messages(
                    "request-4.key28"
                  ) /*单据已转入后台处理，您可以离开页面，审批失败的单据会重新显示在待审批列表。*/
                }
              </div>
            </Col>
          </Row>
        </Modal>
      </div>
    );
  }
}

ApproveRequest.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    language: state.main.language,
    approve: state.cache.approve,
    loginUser: state.login.loginUser,
    loginCompany: state.login.loginCompany,
  };
}

const wrappedApproveRequest = Form.create()(ApproveRequest);

export default connect(mapStateToProps)(wrappedApproveRequest);
